package cn.getech.data.development.utils.cloudera;

import com.cloudera.api.ApiRootResource;
import com.cloudera.api.ApiUtils;
import com.cloudera.api.ClouderaManagerClientBuilder;
import com.cloudera.api.model.*;
import com.cloudera.api.v11.RootResourceV11;
import com.cloudera.api.v11.TimeSeriesResourceV11;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.cxf.helpers.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CMUtils {
    private final static Logger LOGGER = LoggerFactory.getLogger(CMUtils.class);

    /**
     * 把CM的日期转换成正常的日期 CM的时间和正常的时间格式有区别，需要转换（相差8小时）
     *
     * @param cmdatestr
     * @return
     */
    public static Date transCMDateToNormal(String cmdatestr) {
        return ApiUtils.newDateFromString(cmdatestr);
    }

    /**
     * 把正常的日期转换成CM的日期，用于传参数 CM的时间和正常的时间格式有区别，需要转换（相差8小时）
     *
     * @return
     */
    public static String transNormalDateToCMDate(Date date) {
        return ApiUtils.printDate(date);
    }

    /***
     * 初始化ApiRootResource 获取数据
     * @param address
     * @param port
     * @param username
     * @param password
     * @return
     */
    public static ApiRootResource  initApiRootResource(String address,Integer port,String username,String password){
        ApiRootResource apiRoot = null;
        try {
            apiRoot = new ClouderaManagerClientBuilder().withHost(address).
                    withPort(Integer.valueOf(port))
                    .withUsernamePassword(username, password).build();
        } catch (Exception e) {
            LOGGER.error("生成ApiRootResource异常！error:{}",e.getMessage());
            e.printStackTrace();
        }
        return apiRoot;
    }

    /**
     * 按照时间范围，查询图表数据
     */
    public static String getTimeSeriesResponse(String address,Integer port,String username,String password,String query, String from, String to) throws Exception {

        //初始化连接
        ApiRootResource apiRoot = initApiRootResource(address,port,username,password);
        if(null == apiRoot){
            throw new Exception("初始化ApiRootResource异常");
        }
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date fromDate = dfs.parse(from);
        Date toDate = dfs.parse(to);
        String fromformat = ApiUtils.printDate(fromDate);
        String toformat = ApiUtils.printDate(toDate);

        long between = (toDate.getTime() - fromDate.getTime());
        int minutes = (int) (between / (1000 * 60));
        String desire = "RAW";
//        if (minutes <= 30) {
//            desire = "RAW";
//        } else if (minutes > 30 && minutes < 300) {
//            desire = "TEN_MINUTELY";
//        } else if (minutes >= 300 && minutes < 1800) {
//            desire = "HOURLY";
//        } else if (minutes >= 1800 && minutes < 10800) {
//            desire = "SIX_HOURLY";
//        } else {
//            desire = "DAILY";
//        }
         if (minutes <= 30) {
            desire = "RAW";
        } else  if(minutes > 30 && minutes <= 1440){
            desire = "TEN_MINUTELY";
        }else if(minutes > 1440 && minutes <= 10080){
            desire = "HOURLY";
        }else{
            desire = "DAILY";
        }
        ApiTimeSeriesRequest atsr = new ApiTimeSeriesRequest();
        atsr.setQuery(query);
        atsr.setFrom(fromformat);
        atsr.setTo(toformat);
        atsr.setDesiredRollup(desire);
        atsr.setMustUseDesiredRollup(true);
        RootResourceV11 v11 = apiRoot.getRootV11();
        TimeSeriesResourceV11 t11 = v11.getTimeSeriesResource();
        Response res = t11.queryTimeSeries(atsr);
        return IOUtils.toString((InputStream) res.getEntity());
    }

    public static String getHttpData(String loginUrl,String dataUrl,String userLabel,String passwdLabel,String userName,String passwd) {
        HttpClient httpClient = new HttpClient();
        // 模拟登陆，按实际服务器端要求选用 Post 或 Get 请求方式
        PostMethod postMethod = new PostMethod(loginUrl);

        NameValuePair[] data = { new NameValuePair(userLabel, userName), new NameValuePair(passwdLabel, passwd) };
        postMethod.setRequestBody(data);
        try {
            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            httpClient.executeMethod(postMethod);
            // 获得登陆后的 Cookie
            Cookie[] cookies = httpClient.getState().getCookies();
            StringBuffer tmpcookies = new StringBuffer();
            for (Cookie c : cookies) {
                tmpcookies.append(c.toString() + ";");
            }
            GetMethod getMethod = new GetMethod(dataUrl);
            getMethod.setRequestHeader("cookie", tmpcookies.toString());
//            postMethod.setRequestHeader("Referer", "http://www.cc");
//            postMethod.setRequestHeader("User-Agent", "www Spot");
            httpClient.executeMethod(getMethod);
            String text = getMethod.getResponseBodyAsString();
            return text;
        } catch (Exception e) {
            LOGGER.error("模拟登录cm异常！error:{}",e.getMessage());
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        String query = "SELECT cpu_percent_across_hosts WHERE entityName = \"1\" AND category = CLUSTER";
        String from = "2020-11-02 01:20:00";
        String end = "2020-11-02 19:45:00";
//        String json = getTimeSeriesResponse("10.74.20.67",7180,"hujizhong","hujizhong",query, from, end);
//        System.out.println(json);

        //http登录，添加cookie并且得到数据
//        String urlPath = "http://bigdata-test-1:7180/cmf/hardware/hosts/hostsOverview.json?clusterId=1";
//        String body = HttpRequest.get(urlPath)
//                .cookie("__utmz=89050504.1596098874.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=89050504.1273194148.1596098874.1596098874.1596183908.2; csrftoken=PF1c5nLCGG0Nzr4BmqcltxPSjNhKIdEQRd6SVl8P57QAwgL9N0aCmiAEyYBBskuC; sessionid=cem51b6gkd5l3hgr5n9ba10xcgokcihf; CLOUDERA_MANAGER_SESSIONID=node0zgm0uo69zyff1m4ve7z90y32023399.node0")
//                .execute().body();
//        System.out.println(body);


        //hostip和账户替换为你自己的
        String loginUrl = "http://bigdata-test-1:7180/j_spring_security_check";
        String dataUrl = "http://bigdata-test-1:7180/cmf/hardware/hosts/hostsOverview.json?clusterId=1";

        String dataUrl1 = "http://bigdata-test-1:7180/cmf/charts/timeSeries";

        // 需登陆后访问的 Url
//        System.out.println(getHttpData(loginUrl,dataUrl,"j_username","j_password","hujizhong", "hujizhong"));
//        System.out.println(getHttpClient(loginUrl,dataUrl,"j_username","j_password","user", "passwd"));


//
//        //解析html文件
//        String queryUrl = "http://bigdata-test-3:8088/cluster/scheduler?openQueues=root.users.hdfs#root.users#root.users.tongxun#root.users.zhongtai";
//        String body = HttpRequest.get(queryUrl)
//                .execute().body();
//        System.out.println(body);
//
//        Reader reader = new StringReader(body);
//        HTMLEditorKit.Parser parser = new ParserDelegator();
//        parser.parse(reader,new HTMLTableParser(),true);
//        reader.close();
//
////        List table = document1.selectNodes("table");
//        System.out.println(1);


    }


//    static class  HTMLTableParser extends HTMLEditorKit.ParserCallback {
//
//        private boolean encounteredATableRow = false;
//        @Override
//        public void handleText(char[] data, int pos) {
//            if(encounteredATableRow) System.out.println(new String(data));
//        }
//        @Override
//        public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
//            if(t == HTML.Tag.DIV){
//                Object classAttribute = a.getAttribute(HTML.Attribute.CLASS);
//                if(null != classAttribute && Objects.equals("info-wrap ui-widget-content ui-corner-bottom",classAttribute.toString())){
//                    encounteredATableRow = true;
//                }
//            }
//        }
//        @Override
//        public void handleEndTag(HTML.Tag t, int pos) {
//            if(t == HTML.Tag.DIV) encounteredATableRow = false;
//        }
//    }
//
//
//    /**
//     * 查询节点信息
//     */
//    public static String getHost() {
//        RootResourceV11 v11 = apiRoot.getRootV11();
//        HostsResourceV10 hosts = v11.getHostsResource();
//        List<ApiHost> hostList = hosts.readHosts(DataView.SUMMARY).getHosts();
//        for (ApiHost apiHost : hostList) {
//            System.out.println(apiHost);
//        }
//
//        return null;
//    }
//
//    /**
//     * 查询节点信息
//     */
//    public static String getHost111() {
//        RootResourceV11 v11 = apiRoot.getRootV11();
//        HostsResourceV10 hosts = v11.getHostsResource();
//        List<ApiHost> hostList = hosts.readHosts(DataView.SUMMARY).getHosts();
//        for (ApiHost apiHost : hostList) {
//            System.out.println(apiHost);
//        }
//        return null;
//    }
//
//    /**
//     * 获取cloudera-manager中所有集群的信息
//     */
//    public static void getAllCluster(){
//        LOGGER.info("开始测试的时间为{},**************开始测试获取ClouderaManager集群信息**************", LocalDate.now());
//        ApiClusterList apiClusterList = apiRoot.getClustersResource().readClusters(DataView.FULL);
//        LOGGER.info("ClouderaManager 共管理了{}个集群",apiClusterList.getClusters().size());
//        for(ApiCluster apiCluster : apiClusterList){
//            ApiCluster apiCluster1 = apiRoot.getClustersResource().readCluster(apiCluster.getName());
//            LOGGER.info("集群名称 {}",apiCluster1.getName());
//            LOGGER.info("集群显示名称 {}",apiCluster1.getDisplayName());
//            LOGGER.info("CDH 版本：{}-{}",apiCluster1.getVersion(),apiCluster.getFullVersion());
//            LOGGER.info("ClusterUrl {}",apiCluster1.getClusterUrl());
//            LOGGER.info("HostUrl {}",apiCluster1.getHostsUrl());
//            LOGGER.info("Cluster Uuid {}",apiCluster1.getUuid());
//            LOGGER.info("集群运行状态 {}",apiCluster1.getEntityStatus());
//        }
//        LOGGER.info("结束测试的时间为{},**************结束测试获取ClouderaManager集群信息**************", LocalDate.now() );
//    }
//
//    /**
//     * 获取cloudera-manager中每个集群的每个主机的详细信息
//     */
//    public static void getAllHost(){
//        LOGGER.info("开始测试的时间为{},**************开始测试集群主机运行状态**************", LocalDate.now());
//        HostsResourceV10 hostsResourceV10 = apiRoot.getHostsResource();
//        List<ApiHost> hostList = hostsResourceV10.readHosts(DataView.SUMMARY).getHosts();
//        LOGGER.info("总共有 {} 台主机组成集群",hostList.size());
//        for(ApiHost apiHost:hostList){
//            LOGGER.info("---------------------------------------------");
//            Host host = formatHost(hostsResourceV10.readHost(apiHost.getHostId()));
//            LOGGER.info("主机Id : {}",host.getHostId());
//            LOGGER.info("主机名： {}",host.getHostName());
//            LOGGER.info("主机IP： {}",host.getIpAddress());
//            LOGGER.info("主机线程数：{}",host.getNumCores());
//            LOGGER.info("上次上报心跳时间 ：{}",host.getLastHeart());
//            LOGGER.info("核心数：{}",host.getNumPhysicalCores());
//            LOGGER.info("机架：{}",host.getRack());
//            LOGGER.info("内存（G）：{}",host.getTotalPhysMemBytes());
//            LOGGER.info("进程：{}", JSON.toJSON(host.getServices()));
//            LOGGER.info("---------------------------------------------");
//        }
//        LOGGER.info("结束测试的时间为{},**************结束测试集群主机运行状态**************",LocalDate.now());
//    }
//
//    public static Host formatHost(ApiHost apiHost){
//        Host host = new Host();
//        List<String> services = new ArrayList<>();
//        host.setHostId(apiHost.getHostId());
//        host.setHostName(apiHost.getHostname());
//        host.setIpAddress(apiHost.getIpAddress());
//        host.setNumCores(apiHost.getNumCores());
//        host.setNumPhysicalCores(apiHost.getNumPhysicalCores());
//        host.setLastHeart(apiHost.getLastHeartbeat().toString());
//        host.setRack(apiHost.getRackId());
//        host.setTotalPhysMemBytes(apiHost.getTotalPhysMemBytes()/1073741824);
//        for(ApiRoleRef apiRoleRef:apiHost.getRoleRefs()){
//            services.add(apiRoleRef.getRoleName());
//        }
//        host.setServices(services);
//        return host;
//    }
//
//    /**
//     * 获取cloudera-manager上所有集群的所有服务的状态（这里只是粗略的，不涉及时间点位的）：
//     */
//    public static void getAllService(){
////        LOGGER.info("开始测试的时间为{},**************开始测试集群服务运行状态**************",LocalDate.now());
//        ApiClusterList apiClusterList = apiRoot.getClustersResource().readClusters(DataView.SUMMARY);
//        for(ApiCluster apiCluster:apiClusterList){
//            LOGGER.info("集群名称：{}",apiCluster.getDisplayName());
//            LOGGER.info("CDH 版本：{}-{}",apiCluster.getVersion(),apiCluster.getFullVersion());
//            ServicesResourceV10 servicesResourceV10 = apiRoot.getClustersResource().getServicesResource(apiCluster.getName());
//            List<ApiService> apiServices = servicesResourceV10.readServices(DataView.FULL).getServices();
//            LOGGER.info("集群总共有：{} 个service 在运行",apiServices.size());
//            for(ApiService apiService:apiServices){
//                Service service = formatService(apiService);
//                LOGGER.info("***********************************");
//                LOGGER.info("service 名称 {}",service.getName());
//                LOGGER.info("service 类型 {}",service.getType());
//                for(Agent agent:service.getAgentList()) {
//                    LOGGER.info("节点名称 {}", agent.getName());
//                    LOGGER.info("节点状态 {}", agent.getStatus());
//                }
//                LOGGER.info("***********************************");
//            }
//        }
//        LOGGER.info("结束测试的时间为{},**************结束测试集群服务运行状态**************",LocalDate.now());
//    }
//
//    public static Service formatService(ApiService apiService){
//        Service service = new Service();
//        List<Agent> agents = new ArrayList<>();
//        service.setName(apiService.getName());
//        service.setType(apiService.getType());
//        for(ApiHealthCheck apiHealthCheck:apiService.getHealthChecks()){
//            Agent agent =new Agent();
//            agent.setName(apiHealthCheck.getName());
//            agent.setStatus(apiHealthCheck.getSummary());
//            agents.add(agent);
//        }
//        service.setAgentList(agents);
//        return service;
//    }
//
//    public static void getAllServiceRoles(){
//        LOGGER.info("开始测试的时间为{},**************开始测试集群各个服务的roles运行状态**************",LocalDate.now());
//        ApiClusterList apiClusterList = apiRoot.getClustersResource().readClusters(DataView.SUMMARY);
//        for(ApiCluster apiCluster:apiClusterList){
//            LOGGER.info("集群名称：{}",apiCluster.getDisplayName());
//            LOGGER.info("CDH 版本：{}-{}",apiCluster.getVersion(),apiCluster.getFullVersion());
//            ServicesResourceV18 servicesResourceV18 = apiRoot.getClustersResource().getServicesResource(apiCluster.getName());
//            List<ApiService> apiServices = servicesResourceV18.readServices(DataView.FULL).getServices();
//            LOGGER.info("集群总共有：{} 个service 在运行",apiServices.size());
//            for(ApiService apiService:apiServices){
//                RolesResourceV11 rolesResourceV11 = servicesResourceV18.getRolesResource(apiService.getName());
//                LOGGER.info("---------------------服务名称是{}---------------------",apiService.getName());
//                for(ApiRole apiRole :rolesResourceV11.readRoles()){
//                    LOGGER.info("***************************",apiRole.getName());
//                    LOGGER.info("role名称 {}",apiRole.getName());
//                    LOGGER.info("role类型 {}",apiRole.getType());
//                    LOGGER.info("所属集群 {}",apiRole.getServiceRef().getClusterName());
//                    LOGGER.info("所属服务 {}",apiRole.getServiceRef().getServiceName());
//                    LOGGER.info("主机ID {}",apiRole.getHostRef().getHostId());
//                    LOGGER.info("roleUrl {}",apiRole.getRoleUrl());
//                    LOGGER.info("role状态 {}",apiRole.getRoleState());
//                    LOGGER.info("运行状态总结 {}",apiRole.getHealthSummary());
//                    LOGGER.info("entityStatus {}",apiRole.getEntityStatus());
//                    LOGGER.info("roleConfigGroupName {}",apiRole.getRoleConfigGroupRef().getRoleConfigGroupName());
//                    LOGGER.info("configStalenessStatus {}",apiRole.getConfigStalenessStatus());
//                    LOGGER.info("haStatus {}",apiRole.getHaStatus());
//                    for(ApiHealthCheck apiHealthCheck:apiRole.getHealthChecks()){
//                        LOGGER.info("health check name {}",apiHealthCheck.getName());
//                        LOGGER.info("health check summary {}",apiHealthCheck.getSummary());
//                        LOGGER.info("health check suppressed {}",apiHealthCheck.getSuppressed());
//                    }
//                    LOGGER.info("***************************");
//                }
//                LOGGER.info("--------------------------------------------------------",apiService.getName());
//            }
//        }
//        LOGGER.info("结束测试的时间为{},**************结束测试集群各个服务的roles运行状态**************",LocalDate.now());
//    }
//
//    /**
//     * 获取cloudera-manager中某个服务的时间序列点位
//     */
//    public static List<Metric> formatApiTimeSeriesResponse(List<ApiTimeSeriesResponse> apiTimeSeriesResponseList){
//        List<Metric> metrics = new ArrayList<>();
//        for(ApiTimeSeriesResponse apiTimeSeriesResponse:apiTimeSeriesResponseList) {
//            List<Data> dataList = new ArrayList<>();
//            List<ApiTimeSeries> apiTimeSeriesList = apiTimeSeriesResponse.getTimeSeries();
//            for (ApiTimeSeries apiTimeSeries : apiTimeSeriesList) {
//                Metric metric = new Metric();
//                metric.setMetricName(apiTimeSeries.getMetadata().getMetricName());
//                metric.setEntityName(apiTimeSeries.getMetadata().getEntityName());
//                metric.setStartTime(apiTimeSeries.getMetadata().getStartTime().toString());
//                metric.setEndTime(apiTimeSeries.getMetadata().getEndTime().toString());
//                for (ApiTimeSeriesData apiTimeSeriesData : apiTimeSeries.getData()) {
//                    Data data = new Data();
//                    data.setTimestamp(apiTimeSeriesData.getTimestamp().toString());
//                    data.setType(apiTimeSeriesData.getType());
//                    data.setValue(apiTimeSeriesData.getValue());
//                    dataList.add(data);
//                }
//                metric.setData(dataList);
//                metrics.add(metric);
//            }
//        }
//        return metrics;
//    }
//
//    public static List<Metric> getServiceMetrics(String query, String startTime , String endTime){
//        TimeSeriesResourceV6 timeSeriesResourceV6 = apiRoot.getTimeSeriesResource();
//        String[] params = new String []{query,startTime,endTime};
//        LOGGER.info("query sql is {} ,startTime is {} ,endTime is now",params);
//
//        LOGGER.info("开始测试的时间为{},**************开始查询某个服务点位状态**************",LocalDate.now());
//        ApiTimeSeriesResponseList response = timeSeriesResourceV6.queryTimeSeries(query,startTime,endTime);
//        List<ApiTimeSeriesResponse> apiTimeSeriesResponseList = response.getResponses();
//        List<Metric> metrics = formatApiTimeSeriesResponse(apiTimeSeriesResponseList);
//        LOGGER.info("查询时间序列点位:{}", JSON.toJSON(metrics));
//        LOGGER.info("结束测试的时间为{},**************结束查询某个服务点位状态**************",LocalDate.now());
//        return metrics;
//    }

}
